package com.zhang.common.codec;

import com.zhang.common.message.ProxyMessage;
import com.zhang.common.message.ProxyMessageUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义编码器
 */
public class MyEncoder extends MessageToByteEncoder<ProxyMessage> {

    /**
     * 日志对象
     */
    static private Logger log = LoggerFactory.getLogger(MyEncoder.class);
    @Override
    protected void encode(ChannelHandlerContext ctx, ProxyMessage msg, ByteBuf out) throws Exception {
        if (null == msg){
            return;
        }
        //最后自动flush
        byte[] bytes = ProxyMessageUtil.encode(msg);
        log.debug("编码的长度{}",bytes.length);
        out.writeInt(bytes.length);
        out.writeBytes(bytes);
    }
}
